import mqtt from 'mqtt'
import {handlePrivateMessage} from "./message"; //引入mqtt依赖
import {getGuid} from "./guid"; //引入mqtt依赖

var client
let mqttConnected = false  //mqtt连接状态，这个可以不要，直接查询client.connected即可
const publishTopic = '/000001'  //发布Topic
const loginInfo = uni.getStorageSync("loginInfo");
const MQTT_IP_ADDRESS = 'mqtt://127.0.0.1:1883' //mqtt地址端口
//mqtt ws 地址端口
export const MQTT_WS_ADDRESS = process.env.MQTT_WS_URL || "mqtt://127.0.0.1:8083";
const MQTT_OPTIONS = {
    connectTimeout: 5000,      //连接超时时间
    clientId: getGuid() +'_user_' + loginInfo.userId,  //clientId不能重复，这里可以随机生成
    username: 'test',         //用户名
    password: 'test',         //密码
    clean: false,
    keepalive: 60 // 设置心跳间隔为60秒: false
}

//创建客户端连接
export function mqttConnect() {
    // client = mqtt.connect('mqtt://' + MQTT_IP, MQTT_OPTIONS, function (err) {
    client = mqtt.connect(MQTT_WS_ADDRESS, MQTT_OPTIONS, function (err) {
        console.log(err)
    })
    this.connectMqtt();
    this.messageMqtt();
    // 测试消息
    // this.mqttPublish("1234")
}
// 建立链接
export function connectMqtt() {
    client.on('connect', function () {
        console.log('mqtt连接成功')
        mqttConnected = true
    })
}
// 重连
export function reconnectMqtt() {
    if (!mqttConnected) {
        client.on('reconnect', function () {
            console.log('mqtt重连成功')
            mqttConnected = true
        })
    }
}
//接收消息
export function messageMqtt() {
    // 我的topic
    let your_topic = "/user/message/" + loginInfo.userId;
    client.on('connect', function () {
        console.log('Connected')
        // 订阅主题
        client.subscribe(your_topic, function (err) {
            console.log("err" + err)
            // if (!err) {
            //     // 给服务器发布消息
            //     client.publish('000001', 'Hello mqtt')
            // }
        })
    })

    // 接收消息
    client.on('message', function (topic, message) {
        // message is Buffer
        console.log(" 收到消息" + message.toString())
        // 接收消息
        let decoder = new TextDecoder("utf-8");
        // Using decode method to get string output
        let str = decoder.decode(message);
        let o = JSON.parse(str);
        handlePrivateMessage(o)
        console.log("收到消息，" + str)
        // client.end()
    })
}



export function mqttPublish(msg) {
    if (mqttConnected) {
        // if(mqttConnected){
        client.publish(publishTopic, msg, {qos: 1, retain: false});//hello mqtt +
        console.log('发布了一条消息', msg)
    } else {
        console.log("MQTT服务器未连接!")

        // uni.showToast({
        //     title: 'MQTT服务器未连接',
        //     icon: 'none'
        // });
    }
}

//断开连接
export function mqttDisconnect() {
    console.log('mqttConnected', mqttConnected)
    console.log('client', client)
    if (mqttConnected) {
        client.end(true)
        mqttConnected = false
    }
}
export function mqttReconnected() {
    if (!mqttConnected) {
        client.on('reconnect', function () {
            console.log('连接成功')
            mqttConnected = true
        })
    }
}
